package com.xuyuli.dao;

import com.xuyuli.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    public int getMatchCount(String userId,String password){
        String sqlStr = " select count(*) from user where userId = ? and password = ? ";
        //return jdbcTemplate.queryForInt(sqlStr,new Object[]{userName,password});
        //queryForInt方法过时 改用queryForObject 在方法的第三个参数写明返回类型 如String 则写成String.class
        return jdbcTemplate.queryForObject(sqlStr,new Object[]{userId,password},Integer.class);
    }

    public User findUserByUserId(final String userId){
        String sqlStr = " select * from user where userId = ? ";
        final User user = new User();
        jdbcTemplate.query(sqlStr, new Object[]{userId},
                new RowCallbackHandler() {
                    @Override
                    public void processRow(ResultSet resultSet) throws SQLException {
                        user.setUserId(userId);
                        user.setUserName(resultSet.getNString("userName"));
                        user.setPassword(resultSet.getNString("password"));
                    }
                });
        return user;
    }


    public int getMatchIdCount(String userId) {
        String sqlStr = " select count(*) from user where userId = ? ";
        return jdbcTemplate.queryForObject(sqlStr,new Object[]{userId},Integer.class);
    }

    public void register(String userId, String userName, String password) {
        String sqlStr = " INSERT INTO user VALUES (?,?,?)";
        jdbcTemplate.update(sqlStr,new Object[]{userId,userName,password});
    }
}
